﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Windows;

namespace CardTest
{
    /// <summary>
    /// Handler the game. This class is designed to code and decode xml messages. It does message handlings in MainWindow's thread.
    /// </summary>
    class GameHandler : System.Windows.Threading.DispatcherObject
    {
        public MessageController messageController;
        private EventHolder Events;

        /// <summary>
        /// Contrustor.
        /// </summary>
        /// <param name="events">The game events.</param>
        public GameHandler(EventHolder events)
        {
            this.Events = events;
            this.messageController = new MessageController(
                delegate(string Message)
                {
                    this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new NewMessage(this.OnReceiveMessage), Message);
                });
        }

        private void OnReceiveMessage(string message)
        {
            string Message = message as string;

        }

        /// <summary>
        /// Defines the returns of the joining.
        /// </summary>
        public enum RegisterReturns { Success, UsedPlayerName, UnKnownError };

        /// <summary>
        /// Join the game.
        /// </summary>
        /// <param name="playerName"></param>
        /// <returns></returns>
        public RegisterReturns Join(string playerName)
        {
            try
            {
                string r = messageController.Register(playerName);
                XDocument doc = XDocument.Parse(r);
                XElement root = doc.Root;
                if (root.Attribute("result").Value == "success")
                    return RegisterReturns.Success;
                else
                    if (root.Element("detail").Value == "UsedPlayerName")
                        return RegisterReturns.UsedPlayerName;
                    else
                        return RegisterReturns.UnKnownError;
            }
            catch
            {
                return RegisterReturns.UnKnownError;
            }
        }

    }
}
